// module.exports = (options) => {
//   console.log('options',options)
//   return new Promise((resolve, reject) => {
//       options = Object.assign(options, {
//           success(result) {
//               if (result.statusCode === 200) {
//                   resolve(result.data);
//               } else {
//                   reject(result);
//               }
//           },
//           fail: reject,
//       });
//       wx.request(options);
//   });
// };
const api = require('api.js');
const config = require('../config.js')
let requestTicketTimeout = null;
let requestTicket = false;

// 获取ticket凭证
const getTicketVoucher = (resolve) => {
    wx.request({
        url: api.getUrl('/ticket'), //仅为示例，并非真实的接口地址
        data: {

        },
        method: 'POST',
        header: {
            'content-type': 'application/json' // 默认值
        },
        success(res) {
            console.log('res', res.data)
            res.data.expiration += (new Date().getTime() / 1000);
            wx.setStorageSync('ticket', JSON.stringify(res.data));
            resolve(res.data.ticket_id)
        },
        fail: data => {
            console.log(data)
        }
    })
}

// 获取凭证
const getTicketRequest = () => {
    return new Promise((resolve, reject) => {
        console.log(wx.getStorageSync('ticket'));
        console.log((new Date().getTime() / 1000));
        
        
        let ticket = wx.getStorageSync('ticket') ? JSON.parse(wx.getStorageSync('ticket')) : {};
        if (ticket && (ticket.expiration > (new Date().getTime() / 1000))) {
            clearTimeout(requestTicketTimeout);
            requestTicket = false;
            resolve(ticket.ticket_id)
        } else {
            console.log('requestTicket',requestTicket);
            
            if (requestTicket) {
                clearTimeout(requestTicketTimeout);
                requestTicketTimeout = setTimeout(() => {
                    requestTicket = false;
                }, 5000);
                setTimeout(() => {
                    resolve('next');
                }, 100);
            } else {
                getTicketVoucher(resolve)
                requestTicket = true;
            }
        }
    })
}

// 请求结果提示
const requestResult = (res,params) => {
    
    if(res.status_code==401){
        wx.showToast({
          title: res.message,
          icon:'success',
          image:'../../image/icon_mypage_yiquxiao.png'
        })
        return
    }else if(res.status_code==422){
        wx.showToast({
            title: res.message,
            icon:'success',
            image:'../../image/icon_mypage_yiquxiao.png'
          })
          return
    }
    return params.opt.success && params.opt.success(res)
}

class httpRequest {
    requestData(params, method = 'GET') {
        getTicketRequest().then((ticket) => {
            console.log('ticket',ticket)
            if (ticket === '') {

            } else if (ticket === 'next') {
                return this.requestData(params, method);
            } else {
                if (params.auth && !wx.getStorageSync('token')) {
                    console.error('需要登录状态');
                    // return
                }

                let {
                    url,
                    data
                } = params
                const baseUrl = 'http://' + config.host + config.basePath
                let contentType = "application/json";
                console.log(baseUrl + url);
                
                const option = {
                    url: baseUrl + url,
                    data,
                    method:method,
                    header: {
                        'content-type': contentType,
                        'X-ticket': ticket,
                    },
                    success:data => {
                        wx.hideLoading({
                          success: (res) => {
                            requestResult(data.data,params)
                          },
                        })
                    },
                    fail:data => {
                        console.log(11111)
                        console.log('fail',data)
                    }
                }
                if (params.auth) {
                    option.header.Authorization = wx.getStorageSync('token')
                }
                wx.showLoading({
                  title: '',
                })
                wx.request(option)
            }
        })
    }
    get(url, data = "", opt, auth = false) {
        let option = {
            url,
            data,
            opt,
            auth
        };
        return this.requestData(option);
    }

    post(url, data, opt, auth = false) {
        let params = {
            url,
            data,
            opt,
            auth
        };
        return this.requestData(params, "POST");
    }
}

export default new httpRequest()